package netWork;

import com.sun.security.ntlm.Server;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoClient {
//客户端
    //需要通过ip和端口号找到服务器
    private String ip;
    private int port;
    Socket socket = null;
    public TcpEchoClient(String ip, int port) throws IOException {
        this.ip = ip;
        this.port = port;
        socket = new Socket(ip,port);
    }
    //
    public void start(){
        //客户端启动
        //请输入请求
        System.out.println("客户端启动");
    try (InputStream inputStream = socket.getInputStream();
         OutputStream outputStream = socket.getOutputStream()){
        Scanner scanner = new Scanner(System.in);
        Scanner scannerInput = new Scanner(inputStream);
        PrintWriter printWriter = new PrintWriter(outputStream);
        while (true){
                //从键盘上读取输入的内容
            System.out.println("->");
                String request = scanner.next();
                //把读取的内容构造成请求发送到服务器
                //这里的发送带有换行
                printWriter.println(request);
                printWriter.flush();
                //接收服务器处理好的响应
                String response = scannerInput.next();
                //将响应结果显示到控制台
                System.out.printf("[%s : %d ],req %s resp %s\n",socket.getInetAddress().toString(),socket.getPort(),request,response);
            }
        } catch (IOException e) {
             e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient client = new TcpEchoClient("127.0.0.1",9090);
        client.start();
    }
}
